/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.cvut.fel.taskpro.business.support;

import cz.cvut.fel.taskpro.business.isupport.IEnviromentBusiness;
import cz.cvut.fel.taskpro.business.isupport.IMail;
import cz.cvut.fel.taskpro.data.entity.*;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Asynchronous;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * This class provide to send e-mail notication based on configuration in
 * Glassfish which support J
 *
 * @author Tom
 */
@Stateless
public class Mail implements Serializable, IMail {

    @Resource(name = "mail/toms-cz.com")
    private Session mailSession;
    private final String signature = "\r\n Best regards, \r\n Martin Tomasek";
    private final String web = "http://icpc.felk.cvut.cz/TaskPro/";
    @EJB
    private IEnviromentBusiness enviromentB;

    @PostConstruct
    public void init() {
    }

    @Override
    public void sendMessage(String mailAddress, String subject, String text) throws TaskProException {
        String mailNotification = enviromentB.getValueOfEnviroment("mail-notification");
        if(mailNotification==null){
            return;
        }
        mailNotification=mailNotification.toLowerCase();
        if (mailNotification.equals("enable")) {
            Message msg = new MimeMessage(mailSession);
            try {
                msg.setSubject(subject);
                msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailAddress));
                try {
                    msg.setText(new String(text.getBytes(), "UTF-8"));
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
                }
                Transport.send(msg);
            } catch (MessagingException ex) {
                throw new TaskProException(10, "The mail to adress: " + mailAddress + " was not sended cause: " + ex.getLocalizedMessage() + "where:"
                        + " " + ex.toString());
            }
        }
    }

    @Asynchronous
    @Override
    public void notifyAddUser(List<TaskProUser> user) throws TaskProException {
        Iterator userIte = user.iterator();
        while (userIte.hasNext()) {
            TaskProUser currUser = (TaskProUser) userIte.next();
            notifyAddUser(currUser);
        }

    }

    @Asynchronous
    @Override
    public void notifyAddUser(TaskProUser userToNotify) throws TaskProException {
        String content = "Dear user " + userToNotify.getName() + " " + userToNotify.getSurname() + ",\r\n your registration to TaskPro is"
                + " now complete. Your login is: " + userToNotify.getLogin() + " and password is: " + userToNotify.getPassword() + " ."
                + " The system is avaiable on " + web + " . " + signature;
        sendMessage(userToNotify.getEmail(), "TaskPro - registration", content);
    }

    @Override
    public void notifyResetPassword(TaskProUser user, String password, String webAddress) throws TaskProException {
        String content = "Dear user " + user.getName() + " " + user.getSurname() + ",\r\n your password has been reseted"
                + ".  Your new password is: " + password + " and login is: " + user.getLogin()
                + " The system is avaiable on " + webAddress + " ." + signature;
        sendMessage(user.getEmail(), "TaskPro - password reset", content);

    }

    @Asynchronous
    @Override
    public void notifyNewAssignment(List<Student> user, List<Assignment> assignment) throws TaskProException {
        Iterator asIt = assignment.iterator();
        while (asIt.hasNext()) {
            Iterator sIt = user.iterator();
            Assignment currAssignment = (Assignment) asIt.next();
            while (sIt.hasNext()) {
                Student currStudent = (Student) sIt.next();
                String content = "Dear user " + currStudent.getName() + " " + currStudent.getSurname() + " ,\r\n there is a new "
                        + "assignmet from subject " + currAssignment.getSubject().getCode() + ". Deadline is  " + currAssignment.getDeadline() + ", start time "
                        + "is " + currAssignment.getDateOfStart() + " and "
                        + "max point which you can earn is " + currAssignment.getMaxScore() + " The system is avaiable on " + web + " ." + signature;
                sendMessage(currStudent.getEmail(), "New assignments", content);
            }
        }
    }

    @Asynchronous
    @Override
    public void notifySendedAssignment(Kantor kantor, AssignmentSubmit assignmentSubmit) throws TaskProException {
        String content = "Dear user " + kantor.getName() + " " + kantor.getSurname() + " ,\r\n there is a new submit "
                + " for assignment which was assigned " + assignmentSubmit.getAssignment().getDateOfAssignment() + " with template name " + assignmentSubmit.getAssignment().getTemplate().getName()
                + " This assignmet is in subject " + assignmentSubmit.getAssignment().getSubject().getCode() + " and was submit by student " + assignmentSubmit.getStudent().getName() + " " + assignmentSubmit.getStudent().getSurname() + " ."
                + "  The system is avaiable on " + web + " ." + signature;
        sendMessage(kantor.getEmail(), "TaskPro - new submiteed assignment", content);
    }
     @Asynchronous
    @Override
    public void notifyRateUser(Kantor raterKantor, AssignmentSubmit notifiedAssignmentSubmit)throws TaskProException {

        if (notifiedAssignmentSubmit.getAssignment().getType() == Assignment.Type.TEAM) {
            List<Student> studentsToNotify = new ArrayList<Student>();
            studentsToNotify.addAll(notifiedAssignmentSubmit.getTeam().getmStudents());
            Iterator stIt=studentsToNotify.iterator();
            while(stIt.hasNext()){
                Student currStudent=(Student) stIt.next();
                String message=createRateMessage(currStudent, notifiedAssignmentSubmit, raterKantor);
                sendMessage(currStudent.getEmail(), "TaskPro - assignment rate", message);
            }
        }
        else{
            String message=createRateMessage(notifiedAssignmentSubmit.getStudent(), notifiedAssignmentSubmit, raterKantor);
                sendMessage(notifiedAssignmentSubmit.getStudent().getEmail(), "TaskPro - assignment rate", message);
        }

       
    }

    private String createRateMessage(Student student, AssignmentSubmit submittedAssignment, Kantor raterKantor) {
        String content = "Dear user " + student.getName() + " " + student.getSurname() + " ,\r\n "
                + " your submitted assignment from " + submittedAssignment.getDateOfSubmit() + " with name " + submittedAssignment.getAssignment().getTemplate().getName()
                + " has been ranked By teacher" + raterKantor.getName() + " " + raterKantor.getSurname() + "You earned " + submittedAssignment.getGrade() + "\r\n"
                + "You give this evaluation:\r\n" + submittedAssignment.getEvaluation() + "\r\n"
                + "  The system is avaiable on " + web + " ." + signature;
        return content;
    }
}
